package com.qf.application.utils.util;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;

public class JwtUtils {

    private  static long tokenExpiration = 1000*60*60*24;

    private static String tokenSignKey = "xmxm55eryiyiyyds";

    public static String createToken(Long userId, String userName) {
        String builder = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .claim("userId", userId)
                .claim("userName", userName)
                .setSubject("JWT-USER")
                .setExpiration(new Date(System.currentTimeMillis()+tokenExpiration))
                .signWith(SignatureAlgorithm.HS256,tokenSignKey)
                .compact();
        return builder;
    }

    public static Long getUserId(String token) {
        if(StringUtils.isEmpty(token)) return null;
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        Integer userId = (Integer)claims.get("userId");
        return userId.longValue();
    }
}
